package TankGame1;

import java.util.Vector;

/**
 * 敌方坦克
 */
public class EnemyTank extends TankModel implements Runnable {
    private MyTank myTank;

    public EnemyTank(int x, int y, int direction, Vector<EnemyTank> enemyTanks, MyTank myTank) {
        super(x, y, direction, enemyTanks);
        this.myTank = myTank;
    }

    @Override
    public void run() {
        int flag = 20; //同一个方向走20次
        double direction = 0.65;
        while (isLive()) {
            double count = Math.random() * 15; //在当前方向上移动的距离
            if (flag-- == 0) {
                direction = Math.random();
                flag = 5;
            }
            moveByDirection((int) count, direction);
            if (Math.random() > 0.9) //发子弹概率
                Shotting(Math.random());
            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void moveByDirection(int count, double direction) {
        if (direction < 0.25) {
            //向上发射子弹
            int res = getY() - (int) count;
            setY(res);
            setDirection(0);
        } else if (direction < 0.5) {
            //向右发射子弹
            int res = getX() + (int) count;
            setX(res);
            setDirection(1);
        } else if (direction < 0.75) {
            //向下发射子弹
            int res = getY() + (int) count;
            setY(res);
            setDirection(2);
        } else {
            //向左发射子弹
            int res = getX() - (int) count;
            setX(res);
            setDirection(3);
        }
    }

    public void Shotting(double flag) {
        if (flag > 0.5 && getShots().size() <= 5) {
            Shot shot = null;
            //根据方向移动
            int dir = getDirection();
            switch (dir) {
                case 0:
                    shot = new Shot(getX() + 20, getY(), 5, dir);
                    break;
                case 2:
                    shot = new Shot(getX() + 20, getY() + 60, 5, dir);
                    break;
                case 1:
                    shot = new Shot(getX() + 60, getY() + 20, 5, dir);
                    break;
                case 3:
                    shot = new Shot(getX(), getY() + 20, 5, dir);
            }
            getShots().add(shot);
            new Thread(shot).start();
        }
    }

    public MyTank getMyTank() {
        return myTank;
    }
}
